package com.laker.autotest.job;


import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Duration;
import java.time.Instant;

@Component
@EnableScheduling
@Slf4j
public class CleanFileJob {
    @Value("${easy.cleanfiles.days:1}")
    private int days;

    @Scheduled(fixedDelayString = "PT1H")
    public void cleanFile() {
        log.info("Starting cleanFile job");
        StopWatch stopWatch = new StopWatch("cleanFile");
        stopWatch.start("delete dir screenshot");
        deleteFiles(Paths.get("screenshot"));
        stopWatch.stop();
        stopWatch.start("delete dir trace");
        deleteFiles(Paths.get("trace"));
        stopWatch.stop();
        stopWatch.start("delete dir videos");
        deleteFiles(Paths.get("videos"));
        stopWatch.stop();
        log.info("cleanFile job completed, {}", stopWatch.prettyPrint());
    }

    @SneakyThrows
    private void deleteFiles(Path directory) {
        // 检查directory是否存在并且是否是一个目录
        if (!Files.exists(directory) || !Files.isDirectory(directory)) {
            return;
        }
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Instant lastModifiedTime = attrs.lastModifiedTime().toInstant();
                Instant sevenDaysAgo = Instant.now().minus(Duration.ofDays(days));
                if (lastModifiedTime.isBefore(sevenDaysAgo)) {
                    boolean deleted = Files.deleteIfExists(file);
                    log.info("Deleted old file: {}, result: {}", file, deleted);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
//                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}
